#!/bin/bash

# 检查是否提供了配置文件路径
if [ -z "$1" ]; then
    echo "Usage: $0 <path_to_config_file>"
    exit 1
fi

# 检查配置文件是否存在
if [ ! -f "$1" ]; then
    echo "Error: Config file '$1' not found."
    exit 1
fi

# 读取配置文件
config_file="$1"
hosts=($(cat "$config_file"))

# 创建一个新的 iTerm2 窗口
osascript -e "tell application \"iTerm\" to create window with default profile"

# 遍历主机数组，为每个主机创建一个标签页并连接 SSH
for host_info in "${hosts[@]}"; do
    # 解析主机信息
    IFS=":" read -r hostname username password tab_name <<< "$host_info"

    # 如果是第一个主机，直接在新窗口中创建第一个标签页
    if [ -z "$first_tab_created" ]; then
        osascript -e "tell application \"iTerm\" to tell current session of current window to write text \"sshpass -p $password ssh -o StrictHostKeyChecking=no $username@$hostname\""
        osascript -e "tell application \"iTerm\" to set name of current session of current window to \"$tab_name\""
        first_tab_created=true
    else
        # 对于后续主机，创建新的标签页
        osascript -e "tell application \"iTerm\" to tell current window to create tab with default profile"
        osascript -e "tell application \"iTerm\" to tell current session of current window to write text \"sshpass -p $password ssh -o StrictHostKeyChecking=no $username@$hostname\""
        osascript -e "tell application \"iTerm\" to set name of current session of current window to \"$tab_name\""
    fi
done